package com.lin.factorial;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;

public class FactorialClient {
	public static final boolean SSL = System.getProperty("ssl") != null;
	public static final String HOST = System.getProperty("host", "127.0.0.1");
	public static final int POST = Integer.parseInt(System.getProperty("port", "8322"));
	public static final int COUNT = Integer.parseInt(System.getProperty("size", "1000"));

	public static void main(String[] args) throws Exception {
		final SslContext sslContext;
		if (SSL){
			sslContext = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
		}else
			sslContext = null;

		NioEventLoopGroup group = new NioEventLoopGroup();
		try{
			Bootstrap bootstrap = new Bootstrap();
			bootstrap.group(group)
					.channel(NioSocketChannel.class)
					.handler(new FactorialClientInitializer(sslContext));
			ChannelFuture future = bootstrap.connect(HOST, POST).sync();

			FactorialClientHandler last = (FactorialClientHandler) future.channel().pipeline().last();
			System.err.format("Factorial of %,d is: %,d", COUNT, last.getFactorial());
		}finally {
			group.shutdownGracefully();
		}
	}
}
